package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type SysExercises struct {
	service.Service
}

// GetPage 获取SysQuestionBank列表
func (e *SysExercises) GetPage(c *dto.SysExercisesGetPageReq, p *actions.DataPermission, list *[]models.SysExercises, count *int64) error {
	var err error
	var data models.SysExercises

	err = e.Orm.Debug().
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Insert 创建SysQuestionBank对象
func (e *SysExercises) Insert(c *dto.SysExercisesInsertReq) (int, error) {
	var err error
	var data models.SysExercises
	var i int64
	err = e.Orm.Model(&data).Where("name = ?", c.Name).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	if i > 0 {
		err = errors.New("题库已存在！")
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	return data.Id, nil
}

func (e *SysExercises) Update(c *dto.SysExercisesUpdateReq) error {
	var err error
	var model = models.SysExercises{}
	var i int64
	err = e.Orm.Model(&model).Where("name = ?", c.Name).Where("id <> ?", c.Id).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	if i > 0 {
		err = errors.New("题库已存在！")
		e.Log.Errorf("db error: %s", err)
		return err
	}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

// Remove 删除SysQuestionBank
func (e *SysExercises) Remove(c *dto.SysExercisesById, p *actions.DataPermission) error {
	var err error
	var data models.SysExercises

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, c.GetId())
	if err = db.Error; err != nil {
		e.Log.Errorf("Error found in  RemoveSysUser : %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// GetSysDeptList 获取组织数据
func (e *SysExercises) getList(linkId int, list *[]models.SysExercisesWare) error {
	var err error
	var data models.SysExercisesWare
	err = e.Orm.Model(&data).Where("question_bank_id = ?", linkId).Find(list).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Call 递归构造组织数据
func (e SysExercises) ExercisesTreeCall(linkId int) (m []models.ExercisesWareTree, err error) {
	var list []models.SysExercisesWare
	err = e.getList(linkId, &list)

	m = make([]models.ExercisesWareTree, 0)
	for i := 0; i < len(list); i++ {
		if list[i].Pid != 0 {
			continue
		}
		s := models.ExercisesWareTree{}
		s.Id = list[i].Id
		s.Name = list[i].Name
		s.QuestionBankId = list[i].QuestionBankId
		s.IsContainExercise = -1
		s.IsFree = list[i].IsFree
		deptsInfo := exercisesWareTreeCall(&list, s)

		m = append(m, deptsInfo)
	}
	return
}

// Call 递归构造组织数据
func exercisesWareTreeCall(deptList *[]models.SysExercisesWare, result models.ExercisesWareTree) models.ExercisesWareTree {
	list := *deptList
	min := make([]models.ExercisesWareTree, 0)
	for j := 0; j < len(list); j++ {
		if result.Id != list[j].Pid {
			continue
		}
		mi := models.ExercisesWareTree{Id: list[j].Id, Name: list[j].Name, Pid: list[j].Pid, QuestionBankId: list[j].QuestionBankId, IsContainExercise: list[j].IsContainExercise, IsFree: list[j].IsFree, Children: []models.ExercisesWareTree{}}
		ms := exercisesWareTreeCall(deptList, mi)
		min = append(min, ms)
	}
	result.Children = min
	return result
}

// Get 获取SysCourse对象
func (e *SysExercises) Get(d *dto.SysExercisesById, p *actions.DataPermission, model *models.SysExercises) error {
	var data models.SysExercises

	err := e.Orm.Model(&data).Debug().
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error

	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		xlog.Errorf("db error: %s", err)
		return err
	}

	if err != nil {
		xlog.Error(err)
		return err
	}

	return nil
}

func (e *SysExercises) Mul(c *dto.SaveChapterSubmitReq, list *[]models.SysQuestionBankLink, ) error {
	var model models.SysQuestionBankLink
	var err error
	err = e.Orm.Debug().Model(model).Where("link_type = ?", c.LinkType).Where("link_id = ?", c.ObjId).Find(&list).Error
	if err != nil {
		return err
	}

	return nil

}
